import json

import requests

from logger import logger


class DingDingRobot:
    MSG_TYPE_TEXT = 'text'
    MSG_TYPE_LINK = 'link'
    MSG_TYPE_MARKDOWN = 'markdown'

    def __init__(self, access_token):
        self.headers = {'Content-Type': 'application/json'}
        self.data = ''
        self.send_url = 'https://oapi.dingtalk.com/robot/send?access_token=' + access_token

    def make_text_msg(self, msg):
        if msg == '' or msg is None:
            raise Exception('msg is null')

        self.data = str({
            "msgtype": self.MSG_TYPE_TEXT,
            "text": {
                "content": msg
            }
        })
        return self

    def make_link_msg(self, title, text, message_url, pic_url=None):
        data = {
            "msgtype": self.MSG_TYPE_LINK,
            "link": {
                "title": title,
                "text": text,
                "picUrl": '' if pic_url is None else pic_url,
                "messageUrl": message_url
            }
        }
        self.data = str(data)
        return self

    def make_markdown_msg(self, title, text):
        data = {
            "msgtype": self.MSG_TYPE_MARKDOWN,
            "markdown": {
                "title": title,
                "text": text,
            }
        }
        self.data = str(data)
        return self

    def send(self):
        result = requests.post(self.send_url, data=self.data, headers=self.headers)
        status = result.status_code
        reason = result.reason
        if status != 200 or reason != 'OK':
            raise Exception("status is " + status, "reason: " + reason, result.text)

        result_obj = json.loads(result.text)
        errcode_ = result_obj['errcode']
        if errcode_ != 0:
            raise Exception(result_obj)


if __name__ == '__main__':
    # robot = DingDingRobot().make_text_msg('test for notice')
    robot = DingDingRobot("xxx")\
        .make_link_msg('A test for Link msg', "I have a dream. a big dream.", "https://www.baidu.com")
    print(robot.data)
    # robot.send()
